package com.imm.da.base.vm

import android.os.Bundle
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.imm.da.base.BaseActivity
import java.lang.reflect.ParameterizedType

/**
 * <p>------------------------------------------------------
 * <p> Copyright (C) 2021 zhangmz, All rights reserved.
 * <p> If there is technical discussion, you can contact zhangmz90@foxmail.com
 * <p>------------------------------------------------------
 * <p> des
 * <p>
 *
 * @author Created by Administrator
 * @date on 2021 2021/11/14 11:56
 */
abstract class BaseVMActivity<VM : ViewModel, VD : ViewDataBinding>(@LayoutRes val resourceId : Int) : BaseActivity() {

    /**
     * ViewModel
     */
    protected val viewModel : VM by lazy {
        val vmClass = (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<VM>
        ViewModelProvider(this).get(vmClass)
    }

    private var _binding : VD? = null

    /**
     * view绑定
     */
    protected val binding get() = _binding!!

    override fun onCreate(savedInstanceState: Bundle?) {
        createBefore()
        super.onCreate(savedInstanceState)

        _binding = DataBindingUtil.setContentView(this, resourceId)
        _binding?.lifecycleOwner = this
        _binding?.executePendingBindings()
        setContentView(_binding?.root)

        initActivity()
    }

    open fun createBefore(){

    }

    abstract fun initActivity()

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }

}